#define UseFirebase //命名Firebase会冲突闪退

using System;
using UnityEngine;
#if UseFirebase && !UNITY_WEBGL
using Firebase;
using Firebase.Auth;
using Firebase.Extensions;
#endif

//官方文档：https://firebase.google.com/docs/unity/setup?authuser=0&%3Bhl=zh-cn&hl=zh-cn
//官方Demo：https://github.com/firebase/quickstart-unity/blob/master/auth/testapp/Assets/Firebase/Sample/Auth/UIHandler.cs
public static class FirebaseHelper
{
    private static string googleWebClientId;
    private static string facebookAppId;

#if UseFirebase && !UNITY_WEBGL
    public static bool isInited { get; private set; }
    private static FirebaseAuth auth;
    public static FirebaseUser currUser { get; private set; }
#endif

    public static bool IsLoggedIn()
    {
#if UseFirebase && !UNITY_WEBGL
        return currUser != null;
#else
        return false;
#endif
    }

    public static void Init(Action<bool> callback)
    {
#if UseFirebase && !UNITY_WEBGL
        if (isInited)
        {
            callback?.Invoke(true);
            return;
        }
        
        facebookAppId = "";
        if (Application.platform == RuntimePlatform.Android)
        {
            //安卓可热更
            AppOptions options = new AppOptions();
            options.ProjectId = "treinadorai-73fa6";
            options.StorageBucket = "treinadorai-73fa6.firebasestorage.app";
            options.ApiKey = "AIzaSyCM-2uqgHfzU6ax45W_9-LM_4CFTV6XH1w";
            options.AppId = "1:123293017799:android:4e8b2de72015659c8940e2";
            FirebaseApp.Create(options);
            googleWebClientId = "762034344540-nur5tiubb765fhqpebglpgonii85a982.apps.googleusercontent.com";
            facebookAppId = "";
        }
        else if (Application.platform == RuntimePlatform.IPhonePlayer)
        {
            // ios需要将 AppId 转换格式后填入Xcode的URL Scheme,无法热更，所以干脆使用 GoogleService-Info.plist 配置文件，不用代码配置
            // AppId转格式规则：冒号改成小横杠，头部加上app-,即：
            // 1:762034344540:ios:06f7c85769b5a8bc290c99变成
            // app-1-762034344540-ios-06f7c85769b5a8bc290c99
            // 转换后填到 Shift+A中的 Firebase IOS Scheme 里
        }
        
        FirebaseApp.CheckAndFixDependenciesAsync().ContinueWithOnMainThread(task =>
        {
            var dependencyStatus = task.Result;
            if (dependencyStatus == DependencyStatus.Available)
            {
                isInited = true;
                auth = FirebaseAuth.DefaultInstance;
                auth.StateChanged += AuthStateChanged;
                Debug.Log($"解析所有 Firebase 依赖项成功");
                callback?.Invoke(true);
            }
            else
            {
                Debug.LogError($"无法解析所有 Firebase 依赖项: {dependencyStatus}");
                callback?.Invoke(false);
            }
        });
#endif
    }

    private static void AuthStateChanged(object sender, EventArgs eventArgs)
    {
#if UseFirebase && !UNITY_WEBGL
        if (auth.CurrentUser != null)
        {
            Debug.Log("登录成功: " + auth.CurrentUser.DisplayName);
            currUser = auth.CurrentUser;
        }
#endif
    }

    //返回Firebase Token，拿去服务端验证
    public static void GoogleSignIn(Action<string> callback)
    {
#if UseFirebase && !UNITY_WEBGL
        var provider = new FederatedOAuthProvider();
        FederatedOAuthProviderData providerData = new FederatedOAuthProviderData()
        {
            ProviderId = "google.com",
            Scopes = new[] { "email", "profile" },
        };
        if (Application.platform == RuntimePlatform.Android)
        {
            providerData.CustomParameters = new System.Collections.Generic.Dictionary<string, string>()
            {
                { "client_id", googleWebClientId }
            };
        }
        provider.SetProviderData(providerData);
        SignInWithProvider(provider, callback);
#endif
    }

    //返回Firebase Token，拿去服务端验证
    public static void FacebookSignIn(Action<string> callback)
    {
#if UseFirebase && !UNITY_WEBGL
        var provider = new FederatedOAuthProvider();
        FederatedOAuthProviderData providerData = new FederatedOAuthProviderData()
        {
            ProviderId = "facebook.com",
            Scopes = new[] { "email", "public_profile" },
        };
        if (Application.platform == RuntimePlatform.Android)
        {
            providerData.CustomParameters = new System.Collections.Generic.Dictionary<string, string>()
            {
                { "client_id", facebookAppId }
            };
        }
        provider.SetProviderData(providerData);
        SignInWithProvider(provider, callback);
#endif
    }

    public static void SignOut()
    {
#if UseFirebase && !UNITY_WEBGL
        if (auth != null && auth.CurrentUser != null)
        {
            auth.SignOut();
            Debug.Log("Firebase 已登出");
        }
        currUser = null;
#endif
    }

#if UseFirebase && !UNITY_WEBGL
    private static async void SignInWithProvider(FederatedOAuthProvider provider, Action<string> callback)
    {
        if (!isInited)
        {
            Debug.LogError("Firebase未初始化");
            callback?.Invoke(null);
            return;
        }
        if (currUser != null)
        {
            string token = await currUser.TokenAsync(false);
            callback?.Invoke(token);
            return;
        }
        auth.SignInWithProviderAsync(provider).ContinueWithOnMainThread(async task =>
        {
            if (task.IsCompleted && !task.IsFaulted && task.Result != null)
            {
                Debug.Log("Firebase 登录成功");
                currUser = task.Result.User;
                string token = await currUser.TokenAsync(false);
                callback?.Invoke(token);
            }
            else if (task.IsFaulted)
            {
                Debug.Log("Firebase 登录失败: " + task.Exception.Message);
                callback?.Invoke(null);
            }
        });
    }
#endif
}
